<template>
	<view class="goodsdetail">
		<page-head :transparent='true'>
			<slot slot="title">{{title.length>10?title.substr(0,10)+'...':title}}</slot>
			<slot slot="right">{{''}}</slot>
		</page-head>
		<view class="goods-detail-row" v-if="businessCode > -1">
			<view class="goods-detail-img">
				<lazy-image class="lazy-image" :realSrc="picUrl"></lazy-image>
				<!-- <image :src="picUrl" mode="aspectFill"></image> -->
			</view>
			<view class="goods-detail-title" v-if="businessCode > -1">{{ skuName }}</view>
			<view class="goods-detail-money" v-if="businessCode > -1">
				<text class="money-text">
					到手价
					<text class="money-price">￥{{ wlPrice_after }}</text>
				</text>
			</view>
			<view style="height: 10px;"></view>
			<view class="goods-detail-coupon" @click="validaUserInfo" v-if="version == 1">
				<view class="coupen-price">
					<view class="coupen-money">抵 ￥{{ discount }}</view>
					<view class="rang-text" v-if="discount == 0">有效期 无</view>
					<view class="rang-text" v-else>有效期 {{ spread_start_at }}-{{ spread_end_at }}</view>
				</view>
				<view class="coupen-time-rang">点击领取</view>
			</view>
			<view class="goods-detail-coupon" @click="judgeRenation" v-else>
				<view class="coupen-price">
					<view class="coupen-money">抵 ￥{{ discount }}</view>
					<view class="rang-text" v-if="discount == 0">有效期 无</view>
					<view class="rang-text" v-else>有效期 {{ spread_start_at }}-{{ spread_end_at }}</view>
				</view>
				<view class="coupen-time-rang">点击领取</view>
			</view>
			<view style="height: 10px;"></view>
			<!-- <view class="goods-detail-btn"><button @click="validaUserInfo">立即兑换</button></view> -->
		</view>

		<!-- 查看详情 -->
		<view class="look-detil" @click="lookDetil" v-if="businessCode > -1">
			查看详情
			<image :class="[detilMsg ? 'rotate' : '']" src="../../static/img/search/down.png" mode="aspectFill"></image>
		</view>

		<view class="products-detail" :class="[detilMsg ? 'products-detail1' : 'products-detail2']">
			<view class="products-detail-img" v-for="(item, index) in detailList" :key="index">
				<image :src="item" mode="aspectFill"></image>
			</view>
		</view>

		<view class="hot-row">
			<text>热门推荐</text>
		</view>
		<tb-goods-list :goodsList="goodsList" @eventClick="toDetail" :loadingText="'我也是有底线的'" :tm="tbOrTm"></tb-goods-list>
		<foot-tab :footerList="footerList" @goSeller="toTb" @goChange="validaUserInfo" v-if="version == 1"></foot-tab>
		<foot-tab :footerList="footerList" @goSeller="toTb" @goChange="judgeRenation" v-else></foot-tab>
		<w-loading text="加载中.." mask="1" click="0" ref="loading"></w-loading>
	</view>
</template>

<script>
	import TbGoodsList from '../../components/tb-goods-list.vue';
	import apptoh5 from '../../common/js/APPtoH5.js';

	let seller = '',
		skuId = '',
		absoluteUrl = '',
		cateId = 0,
		couponAmount = 0,
		tm = false,
		redirect_param = '',
		relationId = '',
		h5Url = '',
		appUrl = '';
	let picUrl = '',
		skuName = '',
		wlPriceAfter = '',
		endTime = '',
		startTime = '';
	export default {
		components: {
			TbGoodsList
		},
		onShow() {
			genCommonData();
		},
		watch: {
			getRelationId() {
				this.iosSaveRelationId(relationId);
			}
		},
		onLoad(event) {
			this.iosSaveRelationId(relationId);
			var that = this;
			seller = event.seller;
			skuId = event.skuId;
			cateId = event.cid;
			couponAmount = event.coupon_amount;
			tm = event.tm;
			that.tbOrTm = tm ? true : false;
			// that.setBackColor();
			that.genGoodsDetail(skuId);
			that.genHotGoodsList(cateId);
			that.spread_start_at = event.startTime.replace('-', '/').replace('-', '/').substring(0, 10);
			that.spread_end_at = event.endTime.replace('-', '/').replace('-', '/').substring(0, 10);
			window.genVersion();
			this.version = window.version;
		},
		data() {
			return {
				goodsList: [],
				picUrl: '',
				skuName: '',
				wlPrice_after: '',
				discount: '',
				spread_start_at: '',
				spread_end_at: '',
				detailList: [],
				detilMsg: false,
				footerList: [],
				tbOrTm: false,
				businessCode: 1,
				title: '',
				version: 0,
			};
		},
		methods: {
			genCommon() {
				const that = this
				let url = window.location.href;
				console.log("url===" + url);
				let reg_url = /^[^\?]+\?([\w\W]+)$/,
					reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
					arr_url = reg_url.exec(url),
					ret = {};
				if (arr_url && arr_url[1]) {
					let str_para = arr_url[1],
						result;
					while ((result = reg_para.exec(str_para)) != null) {
						ret[result[1]] = result[2];
					}
				}
				let token = ret.token;
				if (token != '' && token != 'null' && token != null && token != undefined && token != 'undefined') {
					uni.setStorageSync('token', decodeURI(token));
					uni.setStorageSync('bump', ret.bump);
					uni.setStorageSync('relationId', ret.relationId);
					uni.setStorageSync('mobile', ret.customerId);
				}
			},
			toTb() {
				appNavigateTo(absoluteUrl);
			},
			getUrlParam: function(url, name) {
				let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
				let r = url.substr(1).match(reg);
				if (r != null) return unescape(r[2]);
				return null;
			},
			saveRelation() {
				uni.request({
					url: this.$usereq + '/coupon-customer/customerorderrelation/save',
					method: 'POST',
					header: {
						'blade-auth': decodeURI(uni.getStorageSync('token')) || decodeURI(UrlParam().token),
						'content-type': 'application/json'
					},
					data: {
						relationId: relationId
					},
					success: res => {
						uni.showToast({
							title: '授权成功',
							mask: false,
							duration: 1500
						});
					}
				});
			},
			lookDetil() {
				if (this.detilMsg) {
					this.detilMsg = false;
				} else {
					this.detilMsg = true;
				}
			},
			validaUserInfo() {
				try {
					let userInfo = uni.getStorageSync('token');
					if (userInfo != '' && userInfo != 'null' && userInfo != null && userInfo != undefined && userInfo !=
						'undefined') {
						uni.request({
							url: this.$usereq + '/coupon-customer/rechargeable/consume/validatorDeduction',
							method: 'POST',
							header: {
								'blade-auth': decodeURI(uni.getStorageSync('token')) || decodeURI(UrlParam().token),
								'content-type': 'application/json'
							},
							data: {
								deduction: tm == 'true' ? 4 : 3, //平台id
								deductionAmount: this.discount,
								picUrl: this.picUrl,
								skuId: skuId,
								skuName: this.skuName,
								wlPrice: this.footerList[0].wlPrice,
								wlPriceAfter: this.wlPrice_after,
								endTime: '',
								startTime: '',
								htmlQuanUrl: '',
								appQuanUrl: ''
							},
							success: res => {
								let datas = res.data;
								this.$refs.loading.close();
								if (datas.code == 200) {
									uni.showModal({
										title: '',
										content: '您已兑换过该优惠券，现在去购买吗？',
										showCancel: true,
										cancelText: '取消',
										confirmText: '确定',
										success: res => {
											if (res.confirm) {
												let result = datas.data;
												appNavigateTo(result.htmlQuanUrl)
											}
										}
									});
								} else {
									this.tbChange();
								}
							}
						});
					} else {
						this.valida();
					}
				} catch (e) {
					uni.showModal({
						title: '',
						content: 'error  ' + e,
						showCancel: false,
						success: res => {
							this.valida();
						}
					});
					// this.valida();
				}
			},
			valida() {
				onStartLogin()
			},
			async judgeRenation() {
				try {
					this.$refs.loading.open();
					uni.request({
						url: this.$usereq + '/coupon-customer/rechargeable/consume/validatorDeduction',
						method: 'POST',
						header: {
							'blade-auth': decodeURI(uni.getStorageSync('token')) || decodeURI(UrlParam().token),
							'content-type': 'application/json'
						},
						data: {
							deduction: tm == 'true' ? 4 : 3, //平台id
							deductionAmount: this.discount,
							picUrl: this.picUrl,
							skuId: skuId,
							skuName: this.skuName,
							wlPrice: this.footerList[0].wlPrice,
							wlPriceAfter: this.wlPrice_after,
							endTime: '',
							startTime: '',
							htmlQuanUrl: '',
							appQuanUrl: ''
						},
						success: res => {
							let datas = res.data;
							if (datas.code == 200) {
								this.$refs.loading.close();
								uni.showModal({
									title: '',
									content: '您已兑换过该优惠券，现在去购买吗？',
									showCancel: true,
									cancelText: '取消',
									confirmText: '确定',
									success: res => {
										if (res.confirm) {
											let result = datas.data;
											appNavigateTo(result.htmlQuanUrl)
										}
									}
								});
							} else {
								this.genRelation();
							}
						}
					});
				} catch (e) {
					this.$refs.loading.close();
					console.log('fail to gen relationId');
				}
			},
			genRelation() {
				uni.request({
					url: this.$serverUrl + '/coupon-customer/customerorderrelation/getRelationId',
					method: 'GET',
					header: {
						'blade-auth': decodeURI(uni.getStorageSync('token')) || decodeURI(UrlParam().token),
						'content-type': 'application/json'
					},
					data: {},
					success: res => {
						let datas = res.data;
						if (datas.code == 200) {
							const relationSync = datas.data.relationId;
							// const relationSync = uni.getStorageSync('relationId');
							// console.log('tb gen relationSync===' + relationSync)
							// console.log('relationSync===' + relationSync);
							// this.$refs.loading.						
							this.$refs.loading.close();
							if (relationSync != null && relationSync != 'null' && relationSync != 'undefined' && relationSync != '') {
								uni.setStorageSync('relationId', relationSync);
								this.tbChange();
							} else {
								this.huanTB();
							}
						} else {
							onStartLogin();
						}
					}
				});
				this.$refs.loading.close();
			},
			huanTB() {
				callNative('onTaobaoAuth', '', '', '')
			},
			setupWebViewJavascriptBridge(callback) {
				if (window.WebViewJavascriptBridge) {
					return callback(WebViewJavascriptBridge);
				}
				if (window.WVJBCallbacks) {
					return window.WVJBCallbacks.push(callback);
				}
				document.addEventListener(
					'WebViewJavascriptBridgeReady',
					function() {
						WebViewJavascriptBridge.init(function(message, responseCallback) {
							responseCallback(data);
						});
						callback(WebViewJavascriptBridge)
					},
					false
				);

				window.WVJBCallbacks = [callback];
				var WVJBIframe = document.createElement('iframe');
				WVJBIframe.style.display = 'none';
				WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
				document.documentElement.appendChild(WVJBIframe);
				setTimeout(function() {
					document.documentElement.removeChild(WVJBIframe)
				}, 0);
			},
			iosSaveRelationId(data) {
				this.setupWebViewJavascriptBridge(function(bridge) {
					bridge.registerHandler('iosSaveRelationId', function(data, responseCallback) {
						uni.setStorageSync('relationId', data);
						let responseData = {};
						uni.request({
							url: apptoh5.houUrl + '/coupon-product/myq/tbGoods/unionurl',
							method: 'POST',
							async: true,
							data: {
								itemid: skuId,
								relationid: uni.getStorageSync('relationId')
							},
							success: res => {
								h5Url = res.data.data.coupon_click_url;
								appUrl = h5Url.replace('https', 'taobao');
								apptoh5.tbUnionurl(tm, couponAmount, picUrl, skuId, skuName, wlPriceAfter, endTime, startTime, h5Url,
									appUrl);
								responseData = {
									'urlH5': h5Url.toString(),
									'urlApp': appUrl.toString()
								}
								setTimeout(function() {
									responseCallback(responseData);
								}, 0)
							}
						});
					});
				});
			},
			tbChange() {
				uni.showModal({
					content: '确认使用余额兑换该优惠券，此操作不可撤销？',
					showCancel: true,
					success: res => {
						if (res.confirm) {
							//this.exchangeUrl();
							// this.genRelationId()
							this.unionurl();
						}
					}
				});
			},
			exchangeUrl() {
				try {
					uni.request({
						url: this.$usereq + '/coupon-customer/rechargeable/consume/deduction',
						method: 'POST',
						header: {
							'blade-auth': decodeURI(uni.getStorageSync('token')) || decodeURI(UrlParam().token),
							'content-type': 'application/json'
						},
						data: {
							deduction: tm == 'true' ? 4 : 3, //平台id
							deductionAmount: this.discount,
							picUrl: this.picUrl,
							skuId: skuId,
							skuName: this.skuName,
							wlPrice: this.footerList[0].wlPrice,
							wlPriceAfter: this.wlPrice_after,
							endTime: this.spread_end_at.replace('/', '-').replace('/', '-'),
							startTime: this.spread_start_at.replace('/', '-').replace('/', '-'),
							htmlQuanUrl: encodeURIComponent(h5Url),
							appQuanUrl: encodeURIComponent(appUrl),
						},
						success: res => {
							this.$refs.loading.close();
							let datas = res.data;
							if (datas.code == 200) {
								uni.showToast({
									icon: 'none',
									title: '领取成功'
								});
								this.toAppSwitch();
							} else if (datas.code == -200) {
								uni.showModal({
									title: '',
									content: '您已兑换过该优惠券，现在去购买吗？',
									showCancel: true,
									cancelText: '取消',
									confirmText: '确定',
									success: res => {
										if (res.confirm) {
											this.toAppSwitch();
										}
									},
									fail: () => {},
									complete: () => {}
								});
							} else if (datas.code == 401) {
								uni.showToast({
									icon: 'none',
									title: '正在前往登录页面'
								});
								onStartLogin();
							} else if (datas.code == 20115) {
								uni.showToast({
									icon: 'none',
									title: '正在前往登录页面'
								});
								onStartLogin();
							} else {
								uni.showToast({
									icon: 'none',
									title: datas.msg
								});
							}
						}
					});
				} catch (e) {
					uni.hideLoading();
					console.log(e.message);
				}
			},
			genRelationId() {
				let relationId = uni.getStorageSync('relationId');
				if (relationId != '' && relationId != null && relationId != 'undefined') {
					console.log('gain relation id');
				} else {
					const url =
						'https://open.21ds.cn/index/extapi/tbkrelationbeian?apkey=80f3e9d1-7e15-04ae-0e69-6aa3e32fa293&infotype=1&offlinescene=4&onlinescene=1&invitercode=M2VV49&return_url=' +
						this.$serverUrl +
						'/tbAuth/redirect/' +
						redirect_param;
					appNavigateTo(url);
				}
			},
			async unionurl() {
				try {
					this.$refs.loading.open();
					let res = await this.$request.post('/coupon-product/myq/tbGoods/unionurl', {
						data: {
							itemid: skuId,
							relationid: uni.getStorageSync('relationId')
						}
					});
					h5Url = res.data.data.coupon_click_url;
					appUrl = h5Url.replace('https', 'taobao');
					this.exchangeUrl();
				} catch (e) {
					this.$refs.loading.close();
					let token = uni.getStorageSync('token');
					uni.showModal({
						title: '',
						content: 'error==' + e,
						showCancel: false,
						cancelText: '',
						confirmText: '',
					});
					console.log(e);
				}
			},
			toAppSwitch() {
				callNative('onStartApp', {
					urlH5: h5Url,
					urlApp: appUrl
				}, '', () => {
					appNavigateTo(h5Url);
				});
			},
			async genGoodsDetail(skuId) {
				try {
					uni.showLoading({
						title: 'loading...',
						mask: true
					});
					let res = await this.$request.get('/coupon-product/myq/tbGoods/goodsDetail', {
						data: {
							itemid: skuId,
							couponAmount: couponAmount
						}
					});
					let code = res.data;
					if (code.code == 200) {
						if (code.businessCode > -1) {
							this.businessCode = 1;
							let datas = res.data.data;
							let zfp = datas.zf_price.toString();
							let reg = RegExp(/-/);
							console.log("zfp==" + zfp);
							console.log('zfp.indexOf(' - ')==' + reg.exec(zfp));
							if (reg.exec(zfp) == null) {
								this.businessCode = 1;
								this.title = datas.title;
								this.detailList = datas.small_images.string;
								this.picUrl = datas.pict_url;
								this.skuName = datas.title;
								this.wlPrice_after = datas.zf_price;
								this.discount = parseInt(couponAmount);
								// this.setTitle(this.skuName);
								absoluteUrl = datas.item_url;
								picUrl = this.picUrl, skuName = this.skuName, wlPriceAfter = this.wlPrice_after;
								this.footerList = [{
									wlPrice: datas.zk_final_price,
									sellerGo: tm == 'true' ? '天猫' : '淘宝',
									wlPrice_after: datas.zf_price,
									item_url: absoluteUrl
								}];
							} else {
								this.businessCode = -1;
								uni.showToast({
									icon: 'none',
									title: '商品已下架'
								})
							}
							uni.hideLoading();
						} else {
							this.businessCode = -1;
							uni.showToast({
								icon: 'none',
								title: '商品已下架'
							})
						}
					}

				} catch (e) {
					console.log(e);
				}
			},
			setBackColor() {
				// #ifdef H5
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: '#FF0000'
				});
				// #endif

				// #ifdef APP-PLUS
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: '#FF0000'
				});
				// #endif

				// #ifdef MP
				uni.setNavigationBarColor({
					frontColor: '#000000',
					background: '#FF0000'
				});
				// #endif
			},
			async genHotGoodsList(cid) {
				try {
					let data = {
						pageno: 1,
						pagesize: 20,
						cat: cateId,
						istmall: tm
					};
					let res = await this.$request.post('/coupon-product/myq/tbGoods/goodsList', {
						data: data
					});
					let datas = res.data;
					let newList = datas.data;
					this.goodsList = newList;
				} catch (e) {
					console.log(e);
				}
			},
			setTitle(title) {
				this.title = title;
				uni.setNavigationBarTitle({
					title: title
				});
			},
			toDetail(e) {
				h5RedirectTo({
					url: '../tbdetail/tbdetail?skuId=' +
						e.num_iid +
						'&cid=' +
						cateId +
						'&title=' +
						e.title +
						'&seller=' +
						seller +
						'&coupon_amount=' +
						e.coupon_amount +
						'&startTime=' +
						e.coupon_start_time +
						'&endTime=' +
						e.coupon_end_time +
						'&tm=' +
						tm
				});
			}
		}
	};
</script>

<style lang="scss"></style>
